//
//  CategoryResponse.swift
//  MyTouTiao
//
//  Created by Yuri on 2018/3/16.
//  Copyright © 2018年 Yuri. All rights reserved.
//

import Foundation
import ObjectMapper
import Moya

class CategoryReponse : Mappable, CustomStringConvertible {
    
    var status : String!
    var count : Int!
    var categories : [HttpCategory]!
    
    required init?(map: Map) {
        //这个一般什么都不用做
    }
    
    // Mappable
    //将JSON中的字段映射到本对象中的字段
    func mapping(map: Map) {
        status <- map["status"]
        count <- map["count"]
        categories <- map["categories"]
    }
    
    var description : String {
        return "CategoryResponse:{"
            + "status=\(status!)"
            + ",count=\(count!)"
            + ",categories=\(categories!)"
            + "}"
    }
    
}

class HttpCategory : Mappable, CustomStringConvertible {
    var id : Int!
    var slug : String!
    var title : String!
    var description1 : String!
    var parent : Int!
    var count : Int!
    
    required init?(map: Map) {
        //这个一般什么都不用做
    }
    
    func mapping(map: Map) {
        id <- map["id"]
        slug <- map["slug"]
        title <- map["title"]
        description1 <- map["description"]
        parent <- map["parent"]
        count <- map["post_count"]
    }
    
    var description: String {
        return "HttpCategory:{"
            + "id=\(id!)"
            + ",slug=\(slug!)"
            + ",title=\(title!)"
            + ",description=\(description1!)"
            + ",parent=\(parent!)"
            + ",count=\(count!)"
            + "}"
    }
}

extension HttpCategory {
    static func getCategorys(completion: @escaping (CategoryReponse?) -> Void) {
        let provider = MoyaProvider<ApiService>()
        provider.request(.category) { (result) in
            switch result {
            case let .success(moyaResponse) :
                let json = try! moyaResponse.mapJSON() as! [String:Any]
                
                if let response = CategoryReponse(JSON: json) {
                    print(response)
                    completion(response)
                }
                
            case let .failure(error) :
                print("请求网络错误.:\(error.failureReason ?? "")")
            }
        }

    }
}
